﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;
using System.IO;
using PlugNT.Custom;
using PlugNT.Common;
using PlugNT.Cms.Core;
using PlugNT.Cms.Model;
using PlugNT.Cms.BLL;
using PlugNT.Cms.Page;

namespace PlugNT.Cms.Web.Admin.Pre_Create
{
    public partial class DoCreate : AdminPage
    {
        private Tables curTables = new Tables();
        private Templet curTemplet = new Templet();
        private Article curArticle = new Article();
        private string clsno = "";
        private string type = "";
        private const string sitemapfile = "sitemap.xml";
        private string currpostfix = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //权限检测
            this.CheckPower();

            clsno = (Request.QueryString["clsno"] == null) ? "" : Request.QueryString["clsno"].Trim();
            type = (Request.QueryString["type"] == null) ? "" : Request.QueryString["type"].Trim();
            currpostfix = (Request.QueryString["currpostfix"] == null) ? WebConfig.TablePostfix : Request.QueryString["currpostfix"].Trim(); 
            
            string error = "";
            if (!IsPostBack)
            {
                //http://localhost:4657/admin/Create/CreatingHtml.aspx?id=35&prefix=news
                if (clsno != "")
                {
                    //右侧根据栏目类别单项生成
                    switch (type)
                    {
                        case "index":
                            error = CreateIndexHtml();
                            break;
                        case "shows":
                            error = CreateShowHtml(); 
                            break;
                        case "list":
                            error = CreateListHtml();
                            break;
                        default:
                            error = "生成静态文件类型未指定①";
                            break;
                    }
                }
                else
                {
                    //批量生成
                    switch (type)
                    {
                        case "id":
                            error = CreateShowHtmlById();
                            break;
                        case "indexs":
                            error = CreateIndexHtmls();
                            break;
                        case "lists":
                            error = CreateListHtmls();
                            break;
                        case "siteindex":
                            error = CreateSiteIndex();
                            break;
                        case "sitemap":
                            error = CreateSiteMap();
                            break;
                        default:
                            error = "生成静态文件类型未指定②";
                            break;
                    }
                }


                if (error.Trim() == "")
                {
                    Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"生成页面成功\";</script>");
                    Response.Flush();
                }
                else
                {
                    Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"" + error + "\";</script>");
                    Response.Flush();
                }

            }
        }

        //根据类别生成聚合页
        public string CreateIndexHtml()
        {
            StringBuilder error = new StringBuilder();
            //根据单个栏目生成
            try
            {

                TablesInfo tinfo =WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
                if (tinfo != null)
                {
                    DataTable dtTemplet = curTemplet.GetListByClsno(clsno);
                    if (dtTemplet.Rows.Count > 0)
                    {

                        DataRow drTemplet = dtTemplet.Rows[0];
                        string t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                        t_createpath = t_createpath + drTemplet["createpath"].ToString();

                        HtmlBuilder html = new HtmlBuilder();
                        html.TablePostFix = currpostfix;
                        string[] arr = drTemplet["indexfile"].ToString().Split(',');
                        foreach (string templetPath in arr)
                        {
                            if (templetPath.Trim() != "")
                            {
                                error.Append(PageBuilder.CreateIndexHtml(html, t_createpath, templetPath, clsno));
                            }
                        }
                    }
                    else
                    {
                        error.Append("模板中没有绑定聚合页类型的文件！");
                    }
                }
                else
                {
                    error.Append("不存在后缀名为" + currpostfix + "的内容表！");
                }
            }
            catch (Exception ex)
            {
                error.Append( SwapErrorString("生成页面错误："+ex.Message + ex.StackTrace));
            }
            return error.ToString();
        }

        //根据类别生成列表页
        public string CreateListHtml()
        {
            StringBuilder error = new StringBuilder();
            //根据单个栏目生成
            try
            {
                TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
                if (tinfo != null)
                {

                    DataTable dtTemplet = curTemplet.GetListByClsno(clsno);
                    if (dtTemplet.Rows.Count > 0)
                    {
                        DataRow drTemplet = dtTemplet.Rows[0];
                        string t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                        t_createpath = t_createpath + drTemplet["createpath"].ToString();

                        HtmlBuilder html = new HtmlBuilder();
                        html.TablePostFix = currpostfix;
                        string[] arr = drTemplet["listfile"].ToString().Split(',');
                        foreach (string templetPath in arr)
                        {
                            if (templetPath.Trim() != "")
                            {
                                error.Append(PageBuilder.CreateListHtml(html, t_createpath, templetPath, clsno));
                            }
                        }
                    }
                    else
                    {
                        error.Append("模板中没有绑定列表页类型的文件！");
                    }
                }
                else
                {
                    error.Append("不存在后缀名为" + currpostfix + "的内容表！");
                }
            }
            catch (Exception ex)
            {
                error.Append(SwapErrorString(ex.Message + ex.StackTrace));
            }
            return error.ToString();
        }

        //根据类别生成内容页
        public string CreateShowHtml()
        {
            string error = "";
            try
            {
                //根据单个栏目生成
                DataTable dtTemplet = curTemplet.GetListByClsno(clsno);
                if (dtTemplet.Rows.Count > 0)
                {
                    DataRow drTemplet = dtTemplet.Rows[0];
                    curArticle.CurPostfix = currpostfix;
                    DataTable dt = curArticle.GetCreateList(clsno);
                    int tCount = dt.Rows.Count;
                    int dCount = 0;
                    int eCount = 0;
                    StringBuilder sbError = new StringBuilder();
                    HtmlBuilder html = new HtmlBuilder();
                    html.TablePostFix = currpostfix;
                    foreach (DataRow dr in dt.Rows)
                    {
                        dCount++;
                        double fCount = Convert.ToDouble(dCount) / Convert.ToDouble(tCount);
                        int flCount = (int)(fCount * 100);
                        error = PageBuilder.CreateShowHtml(html, dr["id"].ToString(), dr["pagename"].ToString(), dr["createpath"].ToString(), drTemplet["showfile"].ToString(), clsno);
                        if (error != "")
                        {
                            sbError.Append("<br />" + error);
                            eCount++;
                        }
                        //Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"生成进度:" + flCount.ToString() + "%\";</script>\n");
                        Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"<div class='lbox'>生成进度：</div><div class='box'><div class='ibox' style='width:" + (flCount * 2).ToString() + "px;'></div></div><div class='lbox'>" + flCount.ToString() + "%</div>\";</script>\n");
                        Response.Flush();
                    }
                    if (eCount != 0)
                    {
                        error = "已生成" + (tCount - eCount).ToString() + "条信息，未生成" + eCount.ToString() + "条信息" + sbError.ToString();
                    }
                }
                else
                {
                    error = "模板中没有绑定指定id的类型！";
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }

        //根据id生成内容页
        public string CreateShowHtmlById()
        {
            string error = "";
            try
            {
                string idstart = (Request.QueryString["idstart"] == null) ? "" : PlugNT.Safe.StringHelper.SqlFilter(Request.QueryString["idstart"].Trim());
                string idend = (Request.QueryString["idend"] == null) ? "" : PlugNT.Safe.StringHelper.SqlFilter(Request.QueryString["idend"].Trim());
                if (idstart.Trim() == "" || idend.Trim() == "")
                {
                    return "请设置开始ID和结束ID";
                }
                else
                {
                    string tmpclsno = "";

                    curArticle.CurPostfix = currpostfix;
                    DataTable dt = curArticle.GetCreateList(int.Parse(idstart), int.Parse(idend));
                    int tCount = dt.Rows.Count;
                    int dCount = 0;
                    int eCount = 0;
                    DataTable dtTemplet = null;

                    StringBuilder sbError = new StringBuilder();
                    HtmlBuilder html = new HtmlBuilder();
                    html.TablePostFix = currpostfix;
                    foreach (DataRow dr in dt.Rows)
                    {
                        dCount++;
                        double fCount = Convert.ToDouble(dCount) / Convert.ToDouble(tCount);
                        int flCount = (int)(fCount * 100);

                        
                        if (tmpclsno != dr["clsno"].ToString())
                        {
                            tmpclsno = dr["clsno"].ToString();
                            dtTemplet = curTemplet.GetListByClsno(tmpclsno);
                        }

                        if (dtTemplet != null && dtTemplet.Rows.Count > 0)
                        {
                            DataRow drTemplet = dtTemplet.Rows[0];
                            error = PageBuilder.CreateShowHtml(html, dr["id"].ToString(), dr["pagename"].ToString(), dr["createpath"].ToString(), drTemplet["showfile"].ToString(), tmpclsno);
                            if (error != "")
                            {
                                sbError.Append("<br />" + error);
                                eCount++;
                            }
                        }
                        else
                        {
                            sbError.Append("<br />ID为" + dr["id"].ToString() + "的数据没有绑定模板");
                            eCount++;
                        }

                        //Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"生成进度:" + flCount.ToString() + "%\";</script>\n");
                        Response.Write("<script>parent.document.getElementById(\"loading\").innerHTML=\"<div class='lbox'>生成进度：</div><div class='box'><div class='ibox' style='width:" + (flCount * 2).ToString() + "px;'></div></div><div class='lbox'>" + flCount.ToString() + "%</div>\";</script>\n");
                        Response.Flush();
                    }
                    if (eCount != 0)
                    {
                        error = "已生成" + (tCount - eCount).ToString() + "条信息，未生成" + eCount.ToString() + "条信息" + sbError.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }

        //生成聚合
        public string CreateIndexHtmls()
        {
            string error = "";
            try
            {
                TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
                if (tinfo != null)
                {
                    string t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                    error = PageBuilder.CreateIndexHtmls(currpostfix, t_createpath);
                }
                else
                {
                    error="不存在后缀名为" + currpostfix + "的内容表！";
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }

        //生成列表页
        public string CreateListHtmls()
        {
            string error = "";
            try
            {
                TablesInfo tinfo = WebConfig.IsAccess ? curTables.GetAccessTablesInfo() : curTables.GetTablesInfoByPostfix(currpostfix);
                if (tinfo != null)
                {
                    string t_createpath = (tinfo.dicpath == "") ? "/" : "/" + tinfo.dicpath + "/";
                    error = PageBuilder.CreateListHtmls(currpostfix, t_createpath);
                }
                else
                {
                    error = "不存在后缀名为" + currpostfix + "的内容表！";
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }

        //生成首页
        public string CreateSiteIndex()
        {
            string error = "";
            try
            {
                string rootpath = HttpContext.Current.Server.MapPath("/").Trim();
                string filepath = rootpath + WebConfig.IndexPath.Trim().Trim('/').Replace("/", "\\");
                string newfilepath = rootpath + Utils.GetFileName(filepath);

                if (!Utils.BackupFile(filepath, newfilepath, true))
                {
                    error = "生成首页失败";
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }


        //生成站点地图
        public string CreateSiteMap()
        {
            string error = "";
            try
            {
                string filepath = HttpContext.Current.Server.MapPath("/").Trim() + sitemapfile;
                StringBuilder text = new StringBuilder();
                string siteurl = WebConfig.SiteUrl.Trim();
                siteurl = (siteurl.EndsWith("/") ? siteurl.TrimEnd('/') : siteurl);
                //string cmspath = WebConfig.CmsPath;

                text.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                text.AppendLine("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">");
                text.AppendLine("  <url>");
                text.AppendLine("    <loc>" + siteurl + "</loc>");
                text.AppendLine("    <lastmod>" + DateTime.Now.ToString() + "</lastmod>");
                text.AppendLine("    <changefreq>daily</changefreq>");
                text.AppendLine("    <priority>1.0</priority>");
                text.AppendLine("  </url>");
                DataTable tmpDt = curTemplet.GetSiteList();
                //AutoUpdate.Start();  自动更新
                //聚合也和列表页
                foreach (DataRow dr in tmpDt.Rows)
                {
                    //分表中的数据
                    DataTable dt = new Tables().GetList();
                    foreach (DataRow idr in dt.Rows)
                    {
                        string dicpath = idr["dicpath"].ToString().Trim();
                        dicpath = "/" + dicpath + "/";
                        //聚合页
                        if (dr["indexfile"].ToString() != "")
                        {
                            string[] files = dr["indexfile"].ToString().Split(',');
                            foreach (string f in files)
                            {
                                if (f.Trim() != "")
                                {
                                    string tmpFileName = PlugNT.Common.Utils.GetFileName(f);
                                    int tmpFlag = tmpFileName.LastIndexOf(".");
                                    tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                                    string extName = tmpFileName.Substring(tmpFlag).ToLower();
                                    if (!(extName == ".js" || extName == ".css"))   //js,css文件不生成地图
                                    {
                                        text.AppendLine("  <url>");
                                        text.AppendLine("    <loc>" + siteurl + dicpath + dr["createpath"].ToString() + tmpFileName + ".shtml</loc>");
                                        text.AppendLine("    <lastmod>" + DateTime.Now.ToString() + "</lastmod>");
                                        text.AppendLine("    <changefreq>weekly</changefreq>");
                                        text.AppendLine("    <priority>0.8</priority>");
                                        text.AppendLine("  </url>");
                                    }
                                }
                            }
                        }
                        //列表页
                        if (dr["listfile"].ToString() != "")
                        {
                            string[] files = dr["listfile"].ToString().Split(',');
                            foreach (string f in files)
                            {
                                if (f.Trim() != "")
                                {
                                    string tmpFileName = PlugNT.Common.Utils.GetFileName(f);
                                    int tmpFlag = tmpFileName.LastIndexOf(".");
                                    tmpFileName = (tmpFlag > 0) ? tmpFileName.Substring(0, tmpFlag) : tmpFileName;

                                    text.AppendLine("  <url>");
                                    text.AppendLine("    <loc>" + siteurl + dicpath + dr["createpath"].ToString() + tmpFileName + "1.shtml</loc>");
                                    text.AppendLine("    <lastmod>" + DateTime.Now.ToString() + "</lastmod>");
                                    text.AppendLine("    <changefreq>weekly</changefreq>");
                                    text.AppendLine("    <priority>0.8</priority>");
                                    text.AppendLine("  </url>");
                                }
                            }
                        }
                    }
                }
                //动态页面
                foreach (KeyValuePair<string, string> keyValue in WebConfig.AspxTemplets)
                {
                    string[] tmpkv = keyValue.Value.Split('|');
                    bool isCreate = (tmpkv.Length > 1) ? (tmpkv[1].Trim() == "true") : false;
                    if (isCreate)
                    {
                        text.AppendLine("  <url>");
                        text.AppendLine("    <loc>" + siteurl + tmpkv[0] + "</loc>");
                        text.AppendLine("    <lastmod>" + DateTime.Now.ToString() + "</lastmod>");
                        text.AppendLine("    <changefreq>weekly</changefreq>");
                        text.AppendLine("    <priority>0.8</priority>");
                        text.AppendLine("  </url>");
                    }
                }

                text.AppendLine("</urlset>");
                if (!Utils.CreateFile(filepath, text.ToString()))
                {
                    error = "生成首页失败";
                }
            }
            catch (Exception ex)
            {
                error = SwapErrorString("生成页面错误：" + ex.Message + ex.StackTrace);
            }
            return error;
        }


        private string SwapErrorString(string error)
        {
            return error.Replace("\"", "").Replace("'", "").Replace("\r\n", "<br>");
        }
    }
}
